package tech.wetech.admin3.infra;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import tech.wetech.admin3.util.AooJwtUtil;
import io.jsonwebtoken.*;


@Component
@Slf4j
public class AooTokenInterceptor implements HandlerInterceptor {
  @Value("${chechToken}")
  private boolean chechToken;

  @Autowired
  private AooJwtUtil jwtUtil;

///   重写preHandle (在请求处理方法被调用之前 调用)
  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    if(!chechToken){
      return true;
    }
    /**
     * 是否检验token中的用户信息？？
     */
    String authorization = request.getHeader("Authorization");
//    log.info("authorization:{}", authorization);
    if (authorization != null && authorization.startsWith("Bearer ")) {
      String token = authorization.substring(7); // Skip past "Bearer "
      if (!jwtUtil.verifyToken(token)){
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "token无效或过期");
        return false;   // 验证失败,结束请求
      }
      return true;
    }else {
      response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "token为空");
      return false;   // 验证失败,结束请求
    }
  }
}

//   //重写postHandle (请求处理方法调用之后，视图渲染之前 调用)
//  @Override
//  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//    String token = request.getHeader("token");
//
//    // 解析token，获取Claims
//    Claims claims = Jwts.parser().setSigningKey("shenzhou").parseClaimsJws(token).getBody();
//
//    // 从Claims中获取email、status和role
//    String email = claims.get("email", String.class);
//    Integer status = claims.get("status", Integer.class);
//    String role = claims.get("role", String.class);
//    // 创建新的token
//    String newToken = AooJwtUtil.createToken(email, status, role);
//    // 将新的token添加到响应头中
//    response.addHeader("newToken", newToken);
//    System.out.println("newToken--------"+newToken);
//  }
